#!/usr/bin/env python3
# coding=utf-8

import paramiko
import logging
# # import logging
# # logging.basicConfig(level = logging.INFO,format = '%(asctime)s [%(filename)s:%(lineno)d] %(levelname)s %(message)s')
# # logger = logging.getLogger("Main")


import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

# from utils.custom_log import ColoredLogger
# paramikolog = paramiko.util.get_logger("paramiko")
# paramikolog.setLevel(logging.CRITICAL)

from utils.custom_log import log_start
logger = log_start('pyssh')


class SSHProxy(object):
    def __init__(self, hostname, port, username, passwd=None,pkey=None):
        
        self.hostname = hostname
        self.port = port
        self.username = username
        self.password = passwd
        self.private_key_path = pkey
        self.transport = None

    def open(self):
        
        try:
            info = "[ {} ]".format(self.hostname)
            logger.info(info)

            if self.private_key_path:
                private_key = paramiko.RSAKey.from_private_key_file(self.private_key_path)
                self.transport = paramiko.Transport((self.hostname, self.port))
                self.transport.connect(username=self.username, pkey=private_key)
            else:
                self.transport = paramiko.Transport((self.hostname, self.port))
                self.transport.start_client()
                self.transport.auth_password(username=self.username, password=self.password)
        except Exception as e:
            logger.error("{}".format(e))
            self.transport.close()
            
            
      
    def close(self):
        self.transport.close()

    def command(self, cmd,show=False):
        ssh = paramiko.SSHClient()
        ssh._transport = self.transport
       

        if isinstance(cmd,list):
            logger.info(f"命令行列表: {cmd}" )
            for command in cmd:

                if  show  is False:
                    cmd ="{} > /dev/null 2>&1".format(command)
                    stdin, stdout, stderr = ssh.exec_command(command)
                else:
                    cmd_result = stdout.read().decode()

                exit_code = stdout.channel.recv_exit_status()
                if exit_code == 0:
                    if  show:
                        info = "远程执行:{0} \n{1}".format(command,cmd_result)
                        logger.info(info)
                    else:
                        logger.info("=======>  " + command)
                else:
                    error_info = stderr.read().decode().strip()
                    error_msg = "远程执行失败：%s；=======>返回：%s" % (command,error_info)
                    logger.error(error_msg)
                    raise ValueError(error_msg)
        else:
            if  show is False:
                cmd ="{} > /dev/null 2>&1".format(cmd)
                ssh.exec_command(cmd)
            else:
                stdin, stdout, stderr = ssh.exec_command(cmd)
                cmd_result = stdout.read().decode()
                exit_code = stdout.channel.recv_exit_status()

                if exit_code == 0:
                    if  show:
                        info = "远程执行命令: {0}\n{1}".format(cmd,cmd_result)
                        logger.info(info)
                    else:
                        logger.info("=======>  " + cmd)
                else:
                    error_info = stderr.read().decode().strip()
                    error_msg = "远程执行失败：%s；=======>返回：%s" % (cmd,error_info)
                    logger.error(error_msg)
                    raise ValueError(error_msg)


        

    def upload(self, local_path, remote_path):
        sftp = paramiko.SFTPClient.from_transport(self.transport)
        sftp.put(local_path, remote_path)
        sftp.close()

    def __enter__(self):
        self.open()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()


if __name__ == '__main__':

    ##### 命令行列表 #####
    commands = [
    "ifconfig",
    "uptime"
    ]
    ##### 主机列表 #####
    hosts = [
        "192.168.0.110",
    ]

    for host in hosts:

        private_key = "/Users/lijingjing/.ssh/id_rsa"
       # with SSHProxy('192.168.0.120', 22, 'root', pkey=private_key) as ssh:
        with SSHProxy('192.168.0.120', 22, 'root', "123456") as ssh:
            ssh.command(commands)
            # ssh.upload('your.tar', '/data/your.tar')


   

    
    